import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

/**
 * api请求基础url
 * 正式环境，考虑不同部署情况，将api前缀部分分离为单独文件，方便运维根据实际部署情况进行修改
 * 文件上传等不适用request封装的，需要引用basePath使用，不可直接使用VUE_APP_BASE_API
 * @type {string}
 */
export let basePath = (process.env.NODE_ENV === 'production' ? apiPath : '') + process.env.VUE_APP_BASE_API;
export let filePathPrefix = "";
//export let filePathPrefix = (process.env.NODE_ENV === 'production' ? filePath : '') + process.env.VUE_APP_FILE_PATH;
const service = axios.create({
  baseURL: basePath, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    //ajax请求参数统一处理，添加验证签名等
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }

    //url数组类型参数处理为,分割字符串
    for (const p in config.params) {
      if (config.params[p] instanceof Array) {
        config.params[p] = config.params[p].join(",")
      }
    }

    return config
  },
  error => {
    console.log(error);
    return Promise.reject(error)
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    //ajax返回数据通用处理，可以对指定错误码统一处理
    const res = response.data;
    if (res.code) {
      if (res.code === '401') {
        store.dispatch('user/resetLoginStatus');
      } else {
        console.log("res err", res.code);
        Message({
          showClose: true,
          message: res.message,
          type: 'error'
        });
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error);
    Message.error(error.message);
    return Promise.reject(error)
  }
);

export default service
